use actix_web::{get,post,web,App,HttpResponse,HttpServer,Responder};

#[get("/")]
async fn  hello()->impl Responder{
    HttpResponse::Ok().body("hello world")
}

#[post("/echo")]
async fn echo(req_body: String) -> impl Responder {
    HttpResponse::Ok().body(req_body)
}

async fn manual_hello() -> impl Responder {
    HttpResponse::Ok().body("Hey there!")
}

#[actix_web::main]
async fn main()->std::io::Result<()> {
HttpServer::new(||{
    App::new().service(hello)
        .service(echo)
        .route("/hey",web::get().to(manual_hello))
})
    .bind("127.0.0.1:8888")?
    .run()
    .await

    // println!("Hello, world!");
    // let p1 = Point { x: 5, y: 10.4 };
    // let p2 = Point { x: "hello", y: 'C' };
    // let p3 = p1.mixup(p2);
    // println!("p3.x = {}, p3.y = {}", p3.x, p3.y);
    //
    // let tweet = Tweet {
    //     username: String::from("horse_ebooks"),
    //     content: String::from("of course, as you probably already know, people"),
    //     reply: false,
    //     retweet: false,
    // };
    // println!("i new tweet:{}", tweet.summarize());
    //
    // let string1 = String::from("long string is long");
    // {
    //     let string2 = String::from("xyz");
    //     let result = longest(string1.as_str(), string2.as_str());
    //     println!("The longest string is {}", result);
    // }
}

// 泛型
struct Point<T, U> {
    x: T,
    y: U,
}

impl<T, U> Point<T, U> {
    fn mixup<V, W>(self, other: Point<V, W>) -> Point<T, W> {
        Point {
            x: self.x,
            y: other.y,
        }
    }
}

// trait（接口）  相干性
// trait 体中可以有多个方法：一行一个方法签名且都以分号结尾。
pub trait Summary {
    fn summarize(&self) -> String;
    // 默认实现
    // fn summarize(&self) -> String {
    //     String::from("(Read more...)")
    // }
}

// 實現trait
pub struct NewsArticle {
    pub headline: String,
    pub location: String,
    pub author: String,
    pub content: String,
}

impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("{}, by {} ({})", self.headline, self.author, self.location)
    }
}

pub struct Tweet {
    pub username: String,
    pub content: String,
    pub reply: bool,
    pub retweet: bool,
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}

// 使用trait bound 實現共享
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
    let mut largest = list[0];

    for &item in list.iter() {
        if item > largest {
            largest = item;
        }
    }
    largest
}

// 生命週期的主要目標是避免懸垂引用
// 借用檢查器
// 函數簽名種的生命週期註解
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}